﻿using Microsoft.Extensions.DependencyInjection;
using Modules.Cms.Entitys;
using Modules.Device.Entitys;
using PetaPoco;
using Pipelines.Sockets.Unofficial.Arenas;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.Caching;
using PmSoft.DBContext;
using PmSoft.Repositories;
using PmSoft.Utilities;
using System.Reflection.Emit;

namespace Modules.Cms.Repositories;


[UseDI(ServiceLifetime.Scoped)]
public class CmsOrderRepository : Repository<CmsOrder, DefaultDbContext>
{
    public CmsOrderRepository(DefaultDbContext dbContext, IApplicationContext applicationContext) : base(dbContext, applicationContext)
    {
    }

    public IPagedList<CmsOrder> GetCmsOrders(CmsOrderQuery query, int pageIndex, int pageSize) {
        Sql sql = Sql.Builder;
        sql.Select("id")
            .From("cms_order")
            .Where("is_deleted=0");
        if (!string.IsNullOrEmpty(query.Keywords))
            sql.Where("(consignee Like @0 )", "%" + StringUtility.StripSQLInjection(query.Keywords) + "%");
        if (query.DealerId.HasValue) {
            sql.Where("dealer_id=@0", query.DealerId);
        }
        sql.OrderBy("create_dt DESC");
        var result = GetPagingEntities(pageSize, pageIndex, sql);
        return result;
    }

    public IEnumerable<CmsOrder> GetOrdersByDealerId(int dealerId)
    {
        Sql sql = Sql.Builder
        .Select("id")
          .From("cms_order")
          .Where("dealer_id =@0", dealerId);
        return PopulateEntitiesByEntityIds(DbContext.Fetch<int>(sql));
    }

    public IEnumerable<CmsOrder> GetOrdersByDealerIds(IEnumerable<int> dealerIds)
    {
        if (dealerIds == null || dealerIds.Count() == 0)
            return Enumerable.Empty<CmsOrder>();
        Sql sql = Sql.Builder
        .Select("id")
          .From("cms_order")
          .Where("dealer_id in (@0)", dealerIds);
        return PopulateEntitiesByEntityIds(DbContext.Fetch<int>(sql));
    }
}
